// 获取所有文章
import pool from '@/server/db'
import { RowDataPacket } from 'mysql2'
import joi from 'joi'

const schema = joi.object({
  pageSize: joi.string().required(),
  page: joi.string().required(),
})

export default defineEventHandler(async event => {
  const query = await getQuery(event)
  // 数据校验
  try {
    schema.validate(query)
  } catch (error) {
    return r('数据校验错误 ' + error)
  }

  // 查询所有文章
  try {
    const { pageSize, page } = query
    const offset = Number(pageSize) * (Number(page) - 1)
    const [rows] = await pool.query('SELECT * FROM `notes` LIMIT ? OFFSET ?', [
      Number(pageSize),
      offset,
    ])
    if ((rows as RowDataPacket[]).length < 1) {
      return r('查询所有文章失败')
    }
    return r('查询所有文章成功', 1, rows)
  } catch (error) {
    return r('所有文章查询失败:' + error)
  }
})
